package com.qianniu.napi.admin.web;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.mapper.GoodsFanliMapper;
import com.qianniu.napi.admin.mapper.GoodsMapper;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.admin.service.akka.AkkaServer;
import com.qianniu.napi.admin.service.akka.ResourceActor;
import com.qianniu.napi.admin.service.akka.StoreActor;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.ImageUtil;
import com.qianniu.napi.common.util.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.rmi.runtime.Log;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 商品信息
 * </p>
 *
 * @author chenxuebin
 * @since 2018-06-23
 */
@Controller
public class GoodsController {

    private static final Logger logger = LoggerFactory.getLogger(GoodsController.class);

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IBannerService bannerService;
    @Autowired
    private IGoodsSkuService goodsSkuService;
    @Autowired
    private IConfigService configService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private IPintuanService pintuanService;
    @Autowired
    private ICouponTplService couponTplService;
    @Autowired
    private IGoodsCategoryService goodscategoryService;
    @Autowired
    private IFenxiaoService fenxiaoService;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private IDisplayFenleiService displayFenleiService;
    @Autowired
    private IGoodsQunzfService goodsQunzfService;
    @Autowired
    private GoodsFanliMapper goodsFanliMapper;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    @RequestMapping("admin/goods/index")
    public String index(Model model) {
        model.addAttribute("isAdmin", ObjectUtil.getIsAdmin());
        MerchantConfig mc = redisService.getMconfig();
        model.addAttribute("isFenxiao", mc.getIsFenxiao());
        model.addAttribute("isPintuan", -1);
        if (mc.getIsFenxiao() == 1) {
            model.addAttribute("fxlist", getFxinfo());
        } else {
            model.addAttribute("fxlist", null);
        }
        List<DisplayFenlei> fenleis = new ArrayList<DisplayFenlei>();
        DisplayFenlei fenlei = new DisplayFenlei();
        fenlei.setShowname("请选择");
        fenleis.add(fenlei);
        fenleis.addAll(displayFenleiService.selectList(new EntityWrapper<DisplayFenlei>()
                .setSqlSelect("id,showname")
                .eq("state", 1)
                .eq("mpid", ObjectUtil.getMpid()).orderBy("sort")));
        model.addAttribute("fenleis", fenleis);
        model.addAttribute("quanlist", couponTplService.selectList(new EntityWrapper<CouponTpl>()
                .setSqlSelect("id,name")
                .eq("state", 1)
                .eq("mid", ObjectUtil.getMid())));

        List<Config> skulist = configService.selectList(new EntityWrapper<Config>()
                .setSqlSelect("id,name")
                .eq("state", 1)
                .eq("level", 1)
                .eq("type", "guige")
                .eq("mid", ObjectUtil.getMid()));
        model.addAttribute("skulist", skulist);
        model.addAttribute("skusize", (skulist == null || skulist.size() == 0 ? 0 : skulist.size()));

//        List<GoodsCategory> categorys = goodscategoryService.selectList(
//                new EntityWrapper<GoodsCategory>().setSqlSelect("id,name")
//                        .eq("mpid", ObjectUtil.getMpid())
//                        .orderBy("paixu")
//        );
        // 商家类目,全目录 使用缓存到redis
        Wrapper<GoodsCategory> wrapper = new EntityWrapper<GoodsCategory>();
        wrapper.eq("mpid", ObjectUtil.getMpid());
        wrapper.eq("state", 1);

        wrapper.isNull("pid");
        wrapper.orderBy("paixu", true);

        List<GoodsCategory> categorys = new ArrayList<GoodsCategory>();

        List<GoodsCategory> list = goodscategoryService.selectList(wrapper);
        for (GoodsCategory item : list) {
            if (item.getHasChild() == 1) {
                Wrapper<GoodsCategory> nwrapper = new EntityWrapper<GoodsCategory>();
                nwrapper.eq("mpid", ObjectUtil.getMpid());
                nwrapper.eq("state", 1);

                nwrapper.eq("pid", item.getId());
                nwrapper.orderBy("paixu", true);

                List<GoodsCategory> childs = goodscategoryService.selectList(nwrapper);
                for (GoodsCategory child : childs) {
                    GoodsCategory gc = new GoodsCategory();
                    gc.setName(item.getName() + ">" + child.getName());
                    gc.setId(child.getId());
                    categorys.add(gc);
                }
            } else {
                GoodsCategory gc = new GoodsCategory();
                gc.setName(item.getName());
                gc.setId(item.getId());
                categorys.add(gc);
            }
        }

        model.addAttribute("categorys", categorys);
        MerchantApp mapp = redisService.getMApp(ObjectUtil.getMpid());
        model.addAttribute("version", mapp.getVersion());
        return "admin/goods";
    }

    @RequestMapping("/admin/goods/list")
    @ResponseBody
    public Page<Goods> alist(@RequestParam(value = "offset", required = false) Integer offset,
                             @RequestParam(value = "type", required = false) Integer type,
                             @RequestParam(value = "state", required = false) Integer state,
                             @RequestParam(value = "gcategory", required = false) Integer gcategory,
                             @RequestParam(value = "search", required = false) String search,
                             @RequestParam(value = "limit", required = false) Integer limit) {
        logger.debug("======limit=" + limit);
        logger.debug("======offset=" + offset);
        Wrapper<Goods> wrapper = new EntityWrapper<Goods>();
        int utype = ObjectUtil.getUserType();
        if (utype < 39)
            wrapper.eq("mpid", ObjectUtil.getMpid());
        else if (utype < 99)
            wrapper.eq("mid", ObjectUtil.getMid());

        if (gcategory != null) wrapper.eq("cid", gcategory);

        if (type != null && type != 99) wrapper.eq("type", type);
        if (state != null) wrapper.eq("state", state);
//        wrapper.eq("sid", 0);
//        if (status!=null&&status != 99) wrapper.eq("gtype", status);
        if (!Strings.isNullOrEmpty(search))
            wrapper.andNew().like("name", search).or().like("goods_no", search).eq("id", search);

        wrapper.orderBy("id", false);
        Page<Goods> page = goodsService.selectPage(new Page<Goods>(offset / limit + 1, limit), wrapper);
        return page;
    }

    @RequestMapping("/admin/goods/displaylist")
    @ResponseBody
    public Page<Goods> displaylist(@RequestParam(value = "offset", required = false) Integer offset,
                                   @RequestParam(value = "status", required = false) Integer status,
                                   @RequestParam(value = "search", required = false) String search,
                                   @RequestParam(value = "gdcid", required = false) Long gdcid,
                                   @RequestParam(value = "limit", required = false) Integer limit) {
        logger.debug("======limit=" + limit);
        logger.debug("======offset=" + offset);
        Wrapper<Goods> wrapper = new EntityWrapper<Goods>();
//        wrapper.setSqlSelect("");
        wrapper.eq("mpid", ObjectUtil.getMpid());
        wrapper.eq("gdcid", gdcid);
        wrapper.orderBy("id", false);
        Page<Goods> page = goodsService.selectPage(new Page<Goods>(offset / limit + 1, limit), wrapper);
        return page;
    }

    @RequestMapping("/admin/goods/skuadd")
    public String skuadd(GoodsSku bean, BindingResult result, Model model) {
        logger.debug("==========admin/goods/skuadd GoodsSku=" + JSON.toJSONString(bean));
        Goods goods = goodsService.selectById(bean.getGid());
        bean.setMinPrice(goods.getMinPrice());
        bean.setPrice(goods.getPrice());
        bean.setCid(goods.getCid());

        bean.setState(1);
        bean.setMid(goods.getMid());
        bean.setMpid(goods.getMpid());
        bean.setUid(ObjectUtil.getUid());
        bean.setSid(ObjectUtil.getSid());
        if (bean.getPic() == null) bean.setPic(goods.getPic());
        bean.setGtype(goods.getGtype());

        logger.debug("==========start to insert=" + JSON.toJSONString(bean));
        bean.insert();

        Goods ngoods = new Goods();
        ngoods.setId(bean.getGid());
        ngoods.setHasSku(1);
        ngoods.setModifytime(new Date());
        ngoods.setModifier(ObjectUtil.getUid());
        ngoods.updateById();
        return "redirect:index";
    }

    @RequestMapping("/admin/goods/add")
    public String add(Goods bean, BindingResult result, Model model) {
        logger.debug("==========admin/goods/add goods=" + JSON.toJSONString(bean));

        bean.setState(0);
        bean.setCreatetime(new Date());
        bean.setModifytime(new Date());
        bean.setMid(ObjectUtil.getMid());
        bean.setMpid(ObjectUtil.getMpid());
        bean.setSid(ObjectUtil.getSid());
        bean.setUid(ObjectUtil.getUid());

        if (Strings.isNullOrEmpty(bean.getPic()) && !Strings.isNullOrEmpty(bean.getPhotos())) {
            List<String> photos = Arrays.asList(bean.getPhotos().split(";"));
            bean.setPic(photos.get(0));
        }
        bean.setThumb(bean.getPic());
        bean.insert();

        //更新资源文件
        AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                .tell("Goods@" + bean.getId() + "@insert", ActorRef.noSender());

        AkkaServer.system.actorOf(Props.create(StoreActor.class))
                .tell(Constants.AKKA_MSG_GOODS_MODIFY + "@" + bean.getId(), ActorRef.noSender());

        // 清除缓存
        String rkey = Constants.REDIS_GOODS_LIST + bean.getMid() + "_" + ObjectUtil.getMpid() + "_" + bean.getCid() + "_1";
        redisService.del(rkey);

        return "redirect:index";
    }

    @RequestMapping("/admin/goods/yxlist")
    @ResponseBody
    public Page<Goods> yxlist(@RequestParam(value = "offset", required = false) Integer offset,
                              @RequestParam(value = "status", required = false) Integer status,
                              @RequestParam(value = "search", required = false) String search,
                              @RequestParam(value = "type", required = false) Integer type,
                              @RequestParam(value = "limit", required = false) Integer limit) {

        Wrapper<Goods> wrapper = new EntityWrapper<Goods>();
        int utype = ObjectUtil.getUserType();
        if (utype < 39)
            wrapper.eq("mpid", ObjectUtil.getMpid());
        else if (utype < 99)
            wrapper.eq("mid", ObjectUtil.getMid());

        wrapper.eq("type", type);

//        if (status!=null&&status != 99) wrapper.eq("gtype", status);
        if (!Strings.isNullOrEmpty(search))
            wrapper.andNew().like("name", search).or().like("goods_no", search);

        wrapper.orderBy("id", false);
        Page<Goods> page = goodsService.selectPage(new Page<Goods>(offset / limit + 1, limit), wrapper);
        return page;
    }

    @RequestMapping("/admin/goods/setdaili")
    public String setdaili(Long gid, BigDecimal huifei, int fxlevel, Model model) {
        logger.debug("======gid=" + gid);
        logger.debug("======huifei=" + huifei);
        logger.debug("======fxlevel=" + fxlevel);
        Fenxiao fenxiao = fenxiaoService.selectOne(new EntityWrapper<Fenxiao>()
                .eq("mpid", ObjectUtil.getMpid()));
        Map<String, String> map = new HashMap<String, String>();
        JSONObject mja = new JSONObject();
        JSONObject jo = null;

        if (fenxiao == null) {
            model.addAttribute("msg", "请先设置分销信息再添加分销商品");
            return "admin/goods";
        }
        List<Goods> fxgoods = goodsService.selectList(new EntityWrapper<Goods>()
                .eq("fxlevel", fxlevel)
                .eq("mpid", ObjectUtil.getMpid())
                .eq("type", -1));// 分销类型的商品

        // 允许重复添加多个同样价格的分销产品
//        if (fxgoods != null&&fxgoods.size()>0){
//            model.addAttribute("msg", "已存在该分销级别的商品，请添加其他代理级别商品");
//            return "admin/goods";
//        }

        Goods goods = new Goods();
        goods.setId(gid);
        goods.setSaleprice(huifei);
        goods.setFxlevel(fxlevel);
        goods.setType(-1);
        goods.updateById();
        return "redirect:index";
    }

    @RequestMapping("/admin/goods/getGoodsById")
    @ResponseBody
    public Goods getGoodsById(long id) {
        Goods goods = goodsService.selectById(id);
        return goods;
    }

    @RequestMapping("/admin/goods/deleteOne")
    @ResponseBody
    public int deleteOne(long id) {
        boolean isSucc = goodsService.deleteById(id);
        return isSucc ? 1 : 0;
    }

    @RequestMapping("/admin/goods/deleteSkuOne")
    @ResponseBody
    public int deleteSkuOne(long id) {
        boolean isSucc = goodsSkuService.deleteById(id);
        return isSucc ? 1 : 0;
    }

    @RequestMapping("/admin/goods/changeState")
    @ResponseBody
    public String changeState(long id, int state) {
        Goods bean = new Goods();
        bean.setId(id);
        bean.setState(state);
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        goodsService.updateById(bean);
        return "success";
    }

    @RequestMapping("/admin/goods/clone")
    @ResponseBody
    public JsonDO clone(long id) {
        Goods bean = goodsService.selectById(id);
        bean.setId(null);
        bean.setInfo(null);
        bean.setPhotos(null);
        bean.setCreatetime(new Date());
        bean.insert();
        return new JsonDO();
    }

    @RequestMapping("/admin/goods/changeSkuState")
    @ResponseBody
    public String changeSkuState(long id, int state) {
        GoodsSku bean = new GoodsSku();
        bean.setId(id);
        bean.setState(state);
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        goodsSkuService.updateById(bean);
        return "success";
    }

    @RequestMapping("/admin/goods/modify")
    public String modify(Goods bean, BindingResult result) {
        // 字段校验+
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());

        Goods oldbean = goodsService.selectById(bean.getId());

        if (Strings.isNullOrEmpty(bean.getPic())) {
            List<String> pics = Arrays.asList(bean.getPhotos().split(";"));
            bean.setPic(pics.get(0));
        }
        if (Strings.isNullOrEmpty(bean.getCharacteristic())) {
            bean.setCharacteristic(" ");
        }
        if (Strings.isNullOrEmpty(bean.getSharewa())) {
            bean.setSharewa(" ");
        }
        if (Strings.isNullOrEmpty(bean.getJieshao())) {
            bean.setJieshao(" ");
        }
        logger.error("----------------------------------modify goods=" + JSON.toJSONString(bean));
        boolean isSuccc = goodsService.updateById(bean);

        AkkaServer.system.actorOf(Props.create(StoreActor.class))
                .tell(Constants.AKKA_MSG_GOODS_MODIFY + "@" + bean.getId(), ActorRef.noSender());

        //更新资源文件
        AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                .tell("Goods@" + bean.getId() + "@update", ActorRef.noSender());

        // 清楚缓存
        String oldkey = Constants.REDIS_GOODS_LIST + bean.getMid() + "_" + ObjectUtil.getMpid() + "_" + oldbean.getCid() + "_1";
        String rkey = Constants.REDIS_GOODS_LIST + bean.getMid() + "_" + ObjectUtil.getMpid() + "_" + bean.getCid() + "_1";
        redisService.del(oldkey);
        redisService.del(rkey);

        return "redirect:index";
    }

    @RequestMapping("/admin/goods/skumodify")
    public String skumodify(GoodsSku bean, BindingResult result) {
        // 字段校验+
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());

        boolean isSuccc = goodsSkuService.updateById(bean);
        if (isSuccc) {
            return "redirect:index";
        }
        return "error";
    }

    @RequestMapping("/admin/goods/setpintuan")
    public String setpintuan(Goods bean, Model model) {
        Jinfo info = new Jinfo();
        // 字段校验+
        logger.info("======setpintuan bean=" + JSON.toJSONString(bean));
        bean.insertOrUpdate();
        return "redirect:/admin/goods/index";
    }

    @RequestMapping("/admin/goods/setfanli")
    public String setfanli(GoodsFanli bean, Model model) {
        // 字段校验
        logger.info("======setpintuan bean=" + JSON.toJSONString(bean));
        if (bean.getZgfanType() == null || bean.getZgfanType() != 3) {
            logger.info("======setpintuan bean.getZgfanType()=" + bean.getZgfanType());
            bean.setZgfanYwid(null);
        }
        if (bean.getShareBonusType() == null || bean.getShareBonusType() != 3) {
            logger.info("======setpintuan bean.getShareBonusType()=" + bean.getShareBonusType());
            bean.setShareYwid(null);
        }
        GoodsFanli fanli = goodsFanliMapper.selectById(bean.getGid());
        if(fanli==null){
            bean.setCreatetime(new Date());
            bean.setCreator(ObjectUtil.getUid());
        }else{
            bean.setModifytime(new Date());
            bean.setModifier(ObjectUtil.getUid());
        }
        bean.insertOrUpdate();

        return "redirect:index";
    }

    @RequestMapping("/admin/goods/changeNavState")
    @ResponseBody
    public String changeNavState(Long id, int state, String pic) {
        Goods bean = new Goods();
        bean.setId(id);
        bean.setIsNav(state);
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        bean.updateById();

        Banner nav = bannerService.selectOne(new EntityWrapper<Banner>().eq("linktype", 3).eq("link", id));
        int cnt = bannerService.selectCount(new EntityWrapper<Banner>().eq("mid", ObjectUtil.getMid()).eq("state", 1));
        if (nav != null) return "success";

        nav = new Banner();
//        nav.setName(gc.getName());
        nav.setPic(pic);
        nav.setState(1);// 默认1：商品分类导航
        nav.setLink(id.toString());
        nav.setLinktype(3);//0：默认；1：H5详情页；2：商品分类页；3：商品详情页；
        nav.setType(1);
        nav.setSort(cnt + 1);

        nav.setMid(ObjectUtil.getMid());
        nav.setMpid(ObjectUtil.getMpid());
        nav.setUid(ObjectUtil.getUid());
        nav.setState(nav.getState());
        nav.insert();

        // ****** 待完善 ******
        // 系统后台登陆获取不到appid，先默认获取第一个MerchantConfig配置
        logger.info("=============mid=" + ObjectUtil.getMid());
        logger.info("=============appid=" + ObjectUtil.getAppid());
        MerchantConfig mc = redisService.getMconfig();

        if (mc != null) {
            mc.setVersion(1 + mc.getVersion());
            mc.insertOrUpdate();
        }
        if (mc != null && mc.getIsCache() != null && mc.getIsCache() == 1) {
            String rkey = Constants.REDIS_APP_INIT + ObjectUtil.getMpid();
            redisService.del(rkey);
        }

        return "success";
    }


    @RequestMapping("/test/goods/fixmpidgoods")
    @ResponseBody
    public Jinfo fixmpidgoods(@RequestParam("hkyid") long id) {
        Jinfo json = new Jinfo();
        try {

//            List<Goods> list = goodsService.selectList(new EntityWrapper<Goods>().eq("mid", 15).eq("mpid", 5));
            List<Banner> list2 = bannerService.selectList(new EntityWrapper<Banner>().eq("mid", 1).eq("mpid", 1));

            for (Banner item : list2) {
                item.setId(null);
                item.setMid(15l);
                item.setMpid(22l);
                item.insert();
            }

//            List<Goods> list = goodsService.selectList(new EntityWrapper<Goods>().eq("mid", 15).eq("mpid", 5));
            List<Goods> list = goodsService.selectList(new EntityWrapper<Goods>().eq("mid", 1).eq("mpid", 1));

            for (Goods item : list) {
                item.setId(null);
                item.setMid(15l);
                item.setMpid(22l);
                item.insert();
            }
            List<GoodsSku> lists = goodsSkuService.selectList(new EntityWrapper<GoodsSku>().eq("mid", 1));//.eq("mpid", 1));

            for (GoodsSku item : lists) {
                item.setMpid(1l);
                item.updateById();

                item.setId(null);
                item.setMid(15l);
                item.setMpid(22l);
                item.insert();
            }

        } catch (Exception e) {
            logger.error("======api/goods/initzhensuoimg error", e);
            json.setCode(5);
        }
        return json;
    }

    private JSONArray getFxinfo() {
        JSONArray mja = new JSONArray();
        JSONObject jo = null;
        Fenxiao fenxiao = fenxiaoService.selectOne(new EntityWrapper<Fenxiao>()
                .eq("mpid", ObjectUtil.getMpid()));

        if (fenxiao == null) return mja;

//        List<Goods> listfan = goodsService.selectList(new EntityWrapper<Goods>()
//                .eq("mpid", ObjectUtil.getMpid())
//                .eq("type", -1));// 分销类型的商品
//
//        if (listfan != null && listfan.size() > 0) {
//            for (Goods item : listfan) {
//                map.put("fxlevel" + item.getFxlevel().toString(), "1");
//            }
//        }

        for (int i = 1; i <= fenxiao.getFxlevel(); i++) {

            if (i == 1) {
                jo = new JSONObject();
                jo.put("name", fenxiao.getFxname1());
                jo.put("huifei", fenxiao.getHuifei1());
                jo.put("fxlevel", 1);
                mja.add(jo);
            } else if (i == 2) {
                jo = new JSONObject();
                jo.put("name", fenxiao.getFxname2());
                jo.put("huifei", fenxiao.getHuifei2());
                jo.put("fxlevel", 2);
                mja.add(jo);
            } else if (i == 3) {
                jo = new JSONObject();
                jo.put("name", fenxiao.getFxname3());
                jo.put("huifei", fenxiao.getHuifei3());
                jo.put("fxlevel", 3);
                mja.add(jo);
            } else if (i == 4) {
                jo = new JSONObject();
                jo.put("name", fenxiao.getFxname4());
                jo.put("huifei", fenxiao.getHuifei4());
                jo.put("fxlevel", 4);
                mja.add(jo);
            } else if (i == 5) {
                jo = new JSONObject();
                jo.put("name", fenxiao.getFxname5());
                jo.put("huifei", fenxiao.getHuifei5());
                jo.put("fxlevel", 5);
                mja.add(jo);
            } else if (i == 6) {
                jo = new JSONObject();
                jo.put("name", fenxiao.getFxname6());
                jo.put("huifei", fenxiao.getHuifei6());
                jo.put("fxlevel", 6);
                mja.add(jo);
            } else if (i == 7) {
                jo = new JSONObject();
                jo.put("name", fenxiao.getFxname7());
                jo.put("huifei", fenxiao.getHuifei7());
                jo.put("fxlevel", 7);
                mja.add(jo);
            }
        }

        return mja;
    }

    @RequestMapping("/admin/goods/update")
    @ResponseBody
    public JsonDO update(Goods bean) {
        // 字段校验+
        JsonDO info = new JsonDO();
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        bean.updateById();
        return info;
    }

    @RequestMapping("/admin/goods/skulist")
    @ResponseBody
    public Page<GoodsSku> skulist(Long gid) {
        // 字段校验
        Page<GoodsSku> page = goodsSkuService.selectPage(new Page<GoodsSku>(1, 50), new EntityWrapper<GoodsSku>()
                .setSqlSelect("id,name,saleprice,ext1,ext2,ext3,ext4,ext5,extids,state,characteristic,pic,price,stores")
                .eq("gid", gid));

        return page;
    }

    @RequestMapping("/admin/goods/skucfg")
    @ResponseBody
    public JsonDO skucfg(Long pid) {
        // 字段校验+
        JsonDO info = new JsonDO();
        List<Config> cfglist = configService.selectList(new EntityWrapper<Config>()
                .setSqlSelect("id,name")
                .eq("pid", pid)
                .eq("state", 1)
                .orderBy("name")
        );
        info.setData(cfglist);
        return info;
    }

    @RequestMapping("/admin/goods/skucfgitem")
    @ResponseBody
    public JsonDO skucfgitem(Long id) {
        // 字段校验
        JsonDO info = new JsonDO();
        Config cfg = configService.selectById(id);
        Long pid = cfg.getPid();
        List<Config> childs = configService.selectList(new EntityWrapper<Config>()
                .setSqlSelect("id,name")
                .eq("pid", pid)
                .eq("state", 1)
                .orderBy("name")
        );

        List<Config> plist = configService.selectList(new EntityWrapper<Config>()
                .setSqlSelect("id,name")
                .eq("state", 1)
                .eq("level", 1)
                .eq("type", "guige")
                .eq("mid", ObjectUtil.getMid()));


        JSONObject jo = new JSONObject();
        jo.put("childs", childs);
        jo.put("plist", plist);
        jo.put("pid", pid);
        jo.put("cid", id);
        info.setData(jo);
        return info;
    }

    @RequestMapping("/admin/goods/storelist")
    @ResponseBody
    public Page<GoodsStore> storelist(@RequestParam(value = "offset", required = false) Integer offset,
                                      @RequestParam(value = "gid", required = false) Long gid,
                                      @RequestParam(value = "search", required = false) String search,
                                      @RequestParam(value = "state", required = false) Integer state,
                                      @RequestParam(value = "limit", required = false) Integer limit) {
        // 字段校验
        JsonDO info = new JsonDO();
        Page<GoodsStore> page = new Page<GoodsStore>(offset / limit + 1, limit);
        if (gid == null) return page;

        Map<String, String> map = new HashMap<String, String>();
        if (offset == null) offset = 0;
        if (limit == null) limit = 50;


        map.put("offset", offset.toString());
        map.put("limit", limit.toString());
        map.put("gid", gid.toString());
        map.put("mpid", ObjectUtil.getMpid().toString());

        int total = goodsMapper.getGoodsStoreCount(map);
        page.setTotal(total);
        page.setRecords(goodsMapper.getGoodsStoreList(map));

        return page;
    }

    @RequestMapping("/admin/goods/guanlianSPlist")
    @ResponseBody
    public Page<Goods> guanlianSPlist(@RequestParam(value = "offset", required = false) Integer offset,
                                      @RequestParam(value = "gid", required = false) Long gid,
                                      @RequestParam(value = "search", required = false) String search,
                                      @RequestParam(value = "state", required = false) Integer state,
                                      @RequestParam(value = "limit", required = false) Integer limit) {
        // 字段校验
        Page<Goods> page = new Page<Goods>(offset / limit + 1, limit);
        Goods goods = goodsService.selectById(gid);
        Long logisticsId = goods.getLogisticsId();

        Wrapper<Goods> wrapper = new EntityWrapper<Goods>()
                .setSqlSelect("id,name")
                .ne("id", gid)
                .eq("type", 0)
                .ge("gtype", 1)
                .le("gtype", 2)
                .eq("mpid", ObjectUtil.getMpid().toString());

        page = goodsService.selectPage(page, wrapper);

        if (logisticsId != null && page.getRecords().size() > 0) {
            List<Goods> glist = page.getRecords();
            boolean isfound = false;

            for (Goods g : glist) {
                if (g.getId().longValue() == logisticsId.longValue()){
                    g.setState(1);
                    isfound = true;
                }
            }

            if (!isfound) {
                List<Goods> nlist = new ArrayList<>();
                Goods spgoods = goodsService.selectById(logisticsId);
                spgoods.setState(1);
                nlist.add(spgoods);
                for (int i = 0; i < glist.size() - 1; i++) {
                    nlist.add(glist.get(i));
                }
                page.setRecords(nlist);
            }
        }

        return page;
    }

    @RequestMapping("/admin/goods/changegsState")
    @ResponseBody
    public String changegsState(long id, int state) {
        GoodsStore bean = new GoodsStore();
        bean.setId(id);
        bean.setState(state);
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        bean.updateById();
        return "success";
    }

    @RequestMapping("/admin/goods/gsdelete")
    @ResponseBody
    public int gsdelete(long id) {
        return goodsMapper.deletegsById(id);
    }

    @RequestMapping("/admin/goods/getNonegstores")
    @ResponseBody
    public Jinfo getNonegstores(Long gid) {
        Jinfo info = new Jinfo();
        Map<String, String> map = new HashMap<String, String>();
        map.put("mpid", ObjectUtil.getMpid().toString());
        map.put("gid", gid.toString());

        info.setData(goodsMapper.getNonegstores(map));
        return info;
    }

    @RequestMapping("/admin/goods/getgstores")
    @ResponseBody
    public Page<Goods> getgstores(@RequestParam(value = "offset", required = false) Integer offset,
                                  @RequestParam(value = "gid", required = false) Long gid,
                                  @RequestParam(value = "search", required = false) String search,
                                  @RequestParam(value = "limit", required = false) Integer limit) {

        Jinfo info = new Jinfo();
        Map<String, String> map = new HashMap<String, String>();
        map.put("mpid", ObjectUtil.getMpid().toString());
        map.put("gid", gid.toString());
        map.put("skip", offset.toString());
        map.put("size", limit.toString());
        map.put("search", search);

        int total = storeService.selectCount(new EntityWrapper<Store>()
                .eq("state", 1)
                .eq("mpid", ObjectUtil.getMpid()));

        Page page = new Page(offset + 1, limit);
        page.setTotal(total);

        page.setRecords(goodsMapper.getallgstores(map));

        return page;
    }

    @RequestMapping("/admin/goods/guanlianSJ")
    @ResponseBody
    public Jinfo guanlianSJ(Long gid, Long sid) {
        GoodsStore goodsStore = new GoodsStore();
        goodsStore.setGid(gid);
        goodsStore.setSid(sid);
        goodsStore.setMpid(ObjectUtil.getMpid());
        goodsStore.setMid(ObjectUtil.getMid());
        goodsStore.setState(1);
        goodsStore.setCreatetime(new Date());
        goodsStore.insert();

        Jinfo info = new Jinfo();
        return info;
    }

    @RequestMapping("/admin/goods/guanlianSP")
    @ResponseBody
    public Jinfo guanlianSP(Long gid, Long glgid) {
        Goods goods = new Goods();
        goods.setId(gid);
        goods.setLogisticsId(glgid);
        goods.setModifytime(new Date());
        goods.updateById();

        Jinfo info = new Jinfo();
        return info;
    }

    @RequestMapping("/admin/goods/guanlianSJall")
    @ResponseBody
    public Jinfo guanlianSJall(Long gid, String sids) {
        Jinfo info = new Jinfo();
        if (Strings.isNullOrEmpty(sids)) return info;
        List<String> list = Arrays.asList(sids.split(";"));

        for (String item : list) {
            if (Strings.isNullOrEmpty(item)) return info;

            GoodsStore goodsStore = new GoodsStore();
            goodsStore.setGid(gid);
            goodsStore.setSid(Long.valueOf(item));
            goodsStore.setMpid(ObjectUtil.getMpid());
            goodsStore.setMid(ObjectUtil.getMid());
            goodsStore.setState(1);
            goodsStore.setCreatetime(new Date());
            goodsStore.insert();
        }

        return info;
    }

    @RequestMapping("/admin/goods/getQunzf")
    @ResponseBody
    public Jinfo getQunzf(Long gid) {
        Jinfo info = new Jinfo();
        GoodsQunzf goodsQunzf = goodsQunzfService.selectById(gid);
        if (goodsQunzf == null) {
            info.setCode(4);
        } else {
            info.setData(goodsQunzf);
        }
        return info;
    }

    @RequestMapping("/admin/goods/getGoodsFanli")
    @ResponseBody
    public Jinfo getGoodsFanli(Long gid) {
        Jinfo info = new Jinfo();
        GoodsFanli fanli = goodsFanliMapper.selectById(gid);
        if (fanli == null) {
            info.setCode(4);
        } else {
            info.setData(fanli);
        }
        return info;
    }

    @RequestMapping("/admin/goods/setQunzf")
    public String setQunzf(GoodsQunzf goodsQunzf) {
        goodsQunzf.insertOrUpdate();
        Goods goods = new Goods();
        goods.setIsqunzf(goodsQunzf.getState());
        goods.setId(goodsQunzf.getGid());
        goods.updateById();
        return "redirect:index";
    }

    @RequestMapping("/admin/goods/guanlianLinpin")
    @ResponseBody
    public Jinfo guanlianLinpin(Long id, String ywid) {
        Jinfo info = new Jinfo();
        Long hdid = null;
        try {
            hdid = Long.valueOf(ywid);
        } catch (Exception e) {
            info.setCode(1);
            return info;
        }

        Goods ogoods = goodsService.selectOne(new EntityWrapper<Goods>().eq("xmtype", id));
        if (ogoods != null) {
            Goods ngoods = new Goods();
            ngoods.setId(ogoods.getId());
            ngoods.setXmtype("");
            ngoods.setModifytime(new Date());
            ngoods.updateById();
        }

        Goods goods = new Goods();

        goods.setId(hdid);
        goods.setXmtype(id.toString());
        goods.setModifytime(new Date());
        goods.updateById();

        return info;
    }

    private final static String rootsite = "https://img.niucaiduo.com/";

    @RequestMapping("/admin/goods/clearimg")
    @ResponseBody
    public Jinfo clearimg(Long mpid) {
        Jinfo info = new Jinfo();
        if (mpid == null || mpid < 0) return info;
        Integer index = 1;
        Integer limit = 100;
        boolean flag = true;
        String img = "";
        String type = "goods";
        Wrapper<Goods> wrapper = new EntityWrapper<Goods>().setSqlSelect("id,thumb,thumbhd,pic,photos,info,packinglist,afterservice,introduction").eq("mpid", mpid);

        while (flag) {
            Page<Goods> page = goodsService.selectPage(new Page<Goods>(index, limit), wrapper);
            for (Goods item : page.getRecords()) {

                if (!Strings.isNullOrEmpty(item.getThumb())) {
                    img = item.getPic().replace(rootsite, Constants.PATH_IMAGES);
                    ImageUtil.movebak(img, type);
                }

                if (!Strings.isNullOrEmpty(item.getThumbhd())) {
                    img = item.getThumbhd().replace(rootsite, Constants.PATH_IMAGES);
                    ImageUtil.movebak(img, type);
                }

                if (!Strings.isNullOrEmpty(item.getPic())) {
                    img = item.getPic().replace(rootsite, Constants.PATH_IMAGES);
                    ImageUtil.movebak(img, type);
                }

                if (!Strings.isNullOrEmpty(item.getPhotos())) {
                    String[] photos = item.getPhotos().replace(rootsite, Constants.PATH_IMAGES).split(";");
                    for (String p : photos) {
                        img = p;
                        ImageUtil.movebak(img, type);
                    }
                }

                if (!Strings.isNullOrEmpty(item.getInfo())) {
                    String[] photos = item.getInfo().replace(rootsite, Constants.PATH_IMAGES).split(";");
                    for (String p : photos) {
                        img = p;
                        ImageUtil.movebak(img, type);
                    }
                }
                if (!Strings.isNullOrEmpty(item.getPackinglist())) {
                    String[] photos = item.getPackinglist().replace(rootsite, Constants.PATH_IMAGES).split(";");
                    for (String p : photos) {
                        img = p;
                        ImageUtil.movebak(img, type);
                    }
                }
                if (!Strings.isNullOrEmpty(item.getAfterservice())) {
                    String[] photos = item.getAfterservice().replace(rootsite, Constants.PATH_IMAGES).split(";");
                    for (String p : photos) {
                        img = p;
                        ImageUtil.movebak(img, type);
                    }
                }
                if (!Strings.isNullOrEmpty(item.getIntroduction())) {
                    String[] photos = item.getIntroduction().replace(rootsite, Constants.PATH_IMAGES).split(";");
                    for (String p : photos) {
                        img = p;
                        ImageUtil.movebak(img, type);
                    }
                }
            }
            flag = page != null && page.getRecords().size() == limit;
            index++;
            logger.info("==========yasuoGoodsimg flag=" + flag);
            logger.info("==========yasuoGoodsimg index=" + index);
        }

        ImageUtil.restorebak(img, type);

        return info;
    }

}
